package server_multicast;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.StringTokenizer;

import parameters.RlmServerParameters;
import utils.Constants;

/**
 * Klasa koja je zaduzena za procesiranje primljene multicast poruke sa RLM klijenta.
 * 
 * Kao odgovor klijentu, salje se poruka sledeceg formata:
 * <br>
 * SET_SERVER_INFO IP_address:port
 * <br>
 * (Ovde je IP_address adresa RLM servera, a port - port servera na kome se ocekuju zahtevi
 * od RLM klijenata.)
 * 
 * @author Uros Krkic
 */
public class MulticastProcessing extends Thread implements Constants {

	/**
	 * IP adresa klijenta, koja se dobija iz poruke.
	 */
	private String IP_Address = "";

	
	/**
	 * Port serverskog procesa klijenta - dobija se iz poruke.
	 */
	private int port = 0;

	
	/**
	 * Socket, koji ce se kreirati od serveera ka klijentu.
	 */
	private Socket socket;
	
	/**
	 * 
	 */
	private ServerMulticast serverMC;
	
	/**
	 * Konstruktor.
	 * @param message - multicast primljena poruka
	 * @author Uros Krkic
	 */
	public MulticastProcessing(ServerMulticast serverMC, String message) {
		this.serverMC = serverMC;
		
		StringTokenizer tokens = new StringTokenizer(message, " ");
		tokens.nextToken();
		
		String IP_and_PORT = tokens.nextToken();
		
		tokens = new StringTokenizer(IP_and_PORT, ":");
		
		this.IP_Address = tokens.nextToken();
		
		this.port = Integer.parseInt(tokens.nextToken());
		
		this.start();
	}
	

	
	@Override
	public void run() {
		try {
			socket = new Socket(IP_Address, port);
			PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
			
			StringBuffer messageBuffer = new StringBuffer("SET_SERVER_INFO ");
//			messageBuffer.append(InetAddress.getLocalHost().getHostAddress());
			messageBuffer.append(serverMC.getServerMCAddress().getHostAddress());
			messageBuffer.append(":");
			messageBuffer.append(RlmServerParameters.getServerPort());
			
			System.out.println("MULTICAST RESPONSE: " + messageBuffer.toString());
			
			writer.println(messageBuffer.toString());
		}
		catch (Exception e) {
			if (socket != null) {
				try {
					socket.close();
				}
				catch (IOException e1) { }
			}
			
			interrupt();
		}
		
//		interrupt();
	}
	
}
